package com.rop.znyx.common.auth;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.rop.znyx.common.constant.RedisConstant;
import com.rop.znyx.util.JwtHelper;
import com.rop.znyx.vo.user.UserLoginVo;
import lombok.NonNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA
 * User: Rop
 * Date: 2023/7/19
 * Time: 11:01
 * Description:
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    private final RedisTemplate<Object, Object> redisTemplate;

    public UserLoginInterceptor(RedisTemplate<Object, Object> template) {
        redisTemplate = template;
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler) throws Exception {
        this.getUserLoginVo(request);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private void getUserLoginVo(HttpServletRequest request) {
        // 1.从请求头中获取token
        String token = request.getHeader("token");

        // 2.判断token是否为空
        if (StrUtil.isBlank(token)) {
            return;
        }

        // 3.从token中获取userId
        Long userId = JwtHelper.getUserId(token);

        // 4.根据userId到Redis中获取用户信息
        UserLoginVo userLoginVo = Convert.convert(UserLoginVo.class, redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + userId));

        // 5.将用户信息放到ThreadLocal中
        if (ObjectUtil.isNotNull(userLoginVo)) {
            AuthContextHolder.setUserId(userLoginVo.getUserId());
            AuthContextHolder.setWareId(userLoginVo.getWareId());
            AuthContextHolder.setUserLoginVo(userLoginVo);
        }
    }
}
